﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;

public partial class masterpage_user : System.Web.UI.MasterPage
{
    chodientuDataContext db = new chodientuDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        //check login 
        if (Session["user"] != null)
        {

            Login1.Visible = false;
            Login2.Visible = true;
            account.InnerText = Session["user"].ToString();
        }
        else
        {
            Login1.Visible = true;
            Login2.Visible = false;
        }
    }
    //function for login / logout / reg
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        dangnhap(tbxTaiKhoan.Value.ToString(), tbxMatKhau.Value.ToString());
    }

    protected void dangnhap(string tk, string mk)
    {
        var query = db.ACCOUNTs.Where(n => n.USERNAME.Equals(tk) && n.PASSWORD.Equals(mk)).Select(n => n.kindOfUser);
        if (query.Count() == 1)
        {
            Session["user"] = tbxTaiKhoan.Value.ToString();
            Session["type"] = query;
            Response.Redirect(Request.RawUrl);
        }
        else
        {
            tbxMatKhau.Value = "";
        }
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect(Request.RawUrl);
    }

    protected void btn_dangky_Click(object sender, EventArgs e)
    {
        if (!tbx_matkhau.ToString().Equals(tbx_matkhau1.ToString()))
            return;

        Thanhvien tv = new Thanhvien();
        ACCOUNT acc = new ACCOUNT();
        tv.Hoten = tbx_hoten.Value.ToString();
        tv.Username = tbx_taikhoan.Value.ToString();
        tv.Diachi = tbx_diachi.Value.ToString();
        tv.Ngaysinh = DateTime.Parse(tbx_ngaysinh.Text);
        tv.Sotaikhoan = tbx_stk.Value.ToString();
        tv.Diemtichluy = 0;
        tv.dienthoai = tbx_dienthoai.Value.ToString();
        tv.email = tbx_email.Value.ToString();
        tv.tinhthanh = drp_tinhthanh.SelectedValue.ToString();

        acc.USERNAME = tbx_taikhoan.Value.ToString();
        acc.PASSWORD = tbx_matkhau.Value.ToString();
        acc.kindOfUser = 0;

        using (TransactionScope ts = new TransactionScope())
        {
            try
            {
                db.ACCOUNTs.InsertOnSubmit(acc);
                db.SubmitChanges();
                db.Thanhviens.InsertOnSubmit(tv);
                db.SubmitChanges();
                ts.Complete();
                Response.Write("<script>alert('Đăng ký thành công');</script>");
                return;
            }
            catch (Exception)
            {
                Response.Write("<script>alert('Đăng ký không thành công');</script>");
                return;
            }
        }
    }
}
